#!/bin/bash
set -e
set -u
trap onexit INT
trap onexit TERM
trap onexit EXIT

SUCCESS=0
VGLCLIENTPID=-1
PID=-1

onexit()
{
	if [ $SUCCESS -eq 1 ]; then
		echo GREAT SUCCESS!
	else
		echo Some errors were encountered.
	fi
	if [ $PID -ne -1 ]; then
		kill -0 $PID >/dev/null 2>&1 && kill $PID
	fi
	if [ $VGLCLIENTPID -ne -1 ]; then
		kill -0 $VGLCLIENTPID >/dev/null 2>&1 && kill $VGLCLIENTPID
	fi
}

BIN=@CMAKE_RUNTIME_OUTPUT_DIRECTORY@
LIB=@CMAKE_LIBRARY_OUTPUT_DIRECTORY@
SSL=@VGL_USESSL@

NODL=
NOSTEREO=
while [ $# -gt 0 ]; do
	case "$1" in
	-nodl)
		echo "Testing without dlopen() interposer"
		NODL=-nodl
		;;
	-nostereo)
		NOSTEREO=-nostereo
		;;
	esac
	shift
done

which Xvfb >/dev/null 2>&1 || (
	echo Xvfb not found!
	exit 1
)
Xvfb :42 -screen 0 1920x1200x24 >/dev/null 2>&1 & PID=$!
echo Xvfb started as process $PID
sleep 2

# VGL Transport
DISPLAY=:42 $BIN/vglclient >vglclient.log 2>&1 & VGLCLIENTPID=$!
DISPLAY=:42 LD_LIBRARY_PATH=$LIB $BIN/vglrun $NODL -c jpeg $BIN/fakerut $NOSTEREO
if [ "$SSL" = "1" ]; then
	DISPLAY=:42 LD_LIBRARY_PATH=$LIB $BIN/vglrun $NODL -c jpeg +s $BIN/fakerut $NOSTEREO
fi
DISPLAY=:42 LD_LIBRARY_PATH=$LIB VGL_READBACK=sync $BIN/vglrun $NODL -np 2 -c rgb $BIN/fakerut $NOSTEREO
# (we can't test stereo here, because the transport plugin assumes
# quad-buffered, which isn't available with an X proxy.)
DISPLAY=:42 LD_LIBRARY_PATH=$LIB $BIN/vglrun $NODL -trans test $BIN/fakerut -nostereo
kill $VGLCLIENTPID
VGLCLIENTPID=-1

# X11 Transport
DISPLAY=:42 LD_LIBRARY_PATH=$LIB $BIN/vglrun $NODL -c proxy $BIN/fakerut $NOSTEREO
DISPLAY=:42 LD_LIBRARY_PATH=$LIB $BIN/vglrun $NODL -trans test2 $BIN/fakerut $NOSTEREO

kill $PID
PID=-1

SUCCESS=1
